/** @format */
import { getToday } from '../getToday'
import { getTotalCompleteTask, getTodayCompleteTask } from '../task'
import { TASK_RATE_TYPE } from '../../../constants'
import { getUserOrderlist } from '../getUserOrderlist'

export default async function updateOrderGoods(
  context: IContext<IParams>,
  { userInfo, activityInfo }: IControllerInfos
): Promise<IPreUpdateQuery> {
  const taskType = 'order'
  const { reward, itemIds, rateType, times } = activityInfo?.tasks?.[taskType] || {}
  const { completeTimes, taskInfo } = getTotalCompleteTask(taskType, userInfo)
  const { todayCompleteTimes } = getTodayCompleteTask(taskType, userInfo)

  if (!activityInfo?.tasks?.[taskType]) return {}
  // 永久任务且已完成
  if (rateType === TASK_RATE_TYPE.FOREVER && completeTimes) {
    return {}
  }

  // 每日限制完成且完成次数达到限制
  const today = getToday()
  if (rateType === TASK_RATE_TYPE.EVERYDAY && todayCompleteTimes >= times) {
    return {}
  }

  const orderResult = await getUserOrderlist(
    context,
    //@ts-ignore
    userInfo.createTime || activityInfo?.startTime || Date.now(),
    Date.now()
  )

  const itemIdsArr = itemIds.split(',').map(v => +v)

  let projection = {
    $inc: {
      [`remainTimes.${taskType}`]: 0
    },
    $set: {}
  }

  let targetOrders = userInfo?.taskInfo?.[today]?.[taskType] || []
  orderResult.forEach(v => {
    // @ts-ignore
    // 商品订单包含目标商品 且orderId为新订单
    if (itemIdsArr.includes(v.itemId) && !taskInfo.some(order => order.orderId === v.orderId)) {
      if (rateType === TASK_RATE_TYPE.EVERYDAY && targetOrders.length >= times) {
        return
      }
      projection.$inc[`remainTimes.${taskType}`] += +reward
      targetOrders.push({
        itemId: v.itemId,
        orderId: v.orderId,
        payTime: v.payTime,
        tId: v.tId,
        createTime: Date.now()
      })
    }
    if (targetOrders?.length) {
      projection.$set[`taskInfo.${today}.${taskType}`] = targetOrders
    }
  })

  return projection
}
